package com.quancheng.component.requestformat.filter.custom;


import com.quancheng.component.requestformat.util.JsonShapingUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ShapingRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] content;

    public ShapingRequestWrapper(HttpServletRequest request) {
        super(request);
        String requestBody = getRequestContent(request);
        content = JsonShapingUtil.toCamelCase(requestBody).getBytes();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(content);

        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return inputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    private String getRequestContent(ServletRequest request) {

        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }catch(Exception e) {
            System.out.println(e.toString());
        }
        return sb.toString();
    }
}
